package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author: wf
 * @Desc:  用户
 * @Date: 2022-08-23 08:52:59
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){

        if (user.getPhone() == null) {
            throw new CustomException("请输入手机号");
        }
        // 生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        code = "1";
        // 发送验证码
//        SMSUtils.sendMessage("名称", "消息模板", user.getPhone(), code);

        log.info("给{}用户发送验证码：{}", user.getPhone(), code);
        // 将验证码储存起来
        session.setAttribute(user.getPhone(), code);

        return R.success("验证码已发送");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info("客户端用户登录{}",map.toString());

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        if (!StringUtils.isNotEmpty(phone) || !StringUtils.isNotEmpty(code)){
            return R.error("格式不对，请重新输入");
        }
        String sessionCode = null;
        try {
            sessionCode = session.getAttribute(phone).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!code.equals(sessionCode)) {
            return R.error("验证码输入有误");
        }
        // 用手机号去数据库查询是不是新用户
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, phone);
        User tempUser = userService.getOne(lqw);
        if (tempUser == null) {
            // 没有查询到直接新建用户
            tempUser = new User();
            tempUser.setPhone(phone);
            tempUser.setStatus(1);
            userService.save(tempUser);
        }

        session.setAttribute("user", tempUser.getId());
        return R.success(tempUser);
    }

}
